package com.leet.tree;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class LowestCommonAncestornobst {
    private Map<TreeNode,TreeNode> parent = new HashMap<>();
    private Set<TreeNode> visited = new HashSet<>();
    void helper(TreeNode root){
        if(root==null) return;
        if(root.left!=null){
            parent.put(root.left,root);
            helper(root.left);
        }
        if(root.right!=null){
            parent.put(root.right,root);
            helper(root.right);
        }
    }
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        helper(root);
        while(p!=null){
            visited.add(p);
            p = parent.get(p);
        }
        while(q!=null){
            if(visited.contains(q)){
                return q;
            }
            q = parent.get(q);
        }
        return null;
    }
}
